package com.pe.pgn.clubpgn.webapp.controller.programa;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.domain.ClpbPrograma;
import com.pe.pgn.clubpgn.service.ProgramaService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;
import com.pe.pgn.clubpgn.webapp.util.CalendarUtil;
import com.pe.pgn.clubpgn.webapp.util.ValidationUtil;

/**
 * @author Frank
 * */

@Controller
@RequestMapping("/programa/**")
public class ProgramaController extends BaseFormController{

	@Autowired
	private ProgramaService programaService;
	
	@RequestMapping(value = "/programalist.html", method = RequestMethod.GET)
	public void listarProgramas(Model model) {
		
		List<ClpbPrograma> programas = programaService.findListaProgramas();
		model.addAttribute("programas", programas);
		model.addAttribute("programa_date_format", DateTimeFormat.patternForStyle("S-", LocaleContextHolder.getLocale()));
	}
	
	@RequestMapping(value = "/programaform.html", method = RequestMethod.GET)
	public String verPrograma(
		   @RequestParam(value = "id", required = false) Long id,
		   Model modelMap) {

		ClpbPrograma programa = null;
		
		if (id != null) {
			programa = programaService.getProgramaPorID(id);
		}else{
			programa = new ClpbPrograma();
		}
		
		modelMap.addAttribute("programa", programa);
		modelMap.addAttribute("listaunidadmedidas", programaService.findUnidadMedidas());
		return "/programa/programaform";
	}
	
	@RequestMapping(value = "/eliminarprograma.html")
	public String eliminarPrograma(@RequestParam(value = "id", required = false) Long id, 
			HttpServletRequest request, Model modelMap) {

		try {

			if(!programaService.verificarDependencias(id)){ //true = tiene dependencoas
				programaService.eliminarPrograma(id);
				saveMessage(request, getText("programaform.deleted", request.getLocale()));
			}else{
				saveError(request, getText("programaform.dependencias", request.getLocale()));
			}			
			
			return "redirect:programalist.html";
			
		} catch (Exception e) {
			
			saveError(request, getText("errors.general", request.getLocale()));
			ClpbPrograma programa = new ClpbPrograma();
			
			if (id != null) {
				programa = programaService.getProgramaPorID(id);
			}
			
			modelMap.addAttribute("programa", programa);
			modelMap.addAttribute("listaunidadmedidas", programaService.findUnidadMedidas());
			return "/programa/programaform";
		}
	}
	
	@RequestMapping(value = "/programaform.html", method = RequestMethod.POST)
	public String guardarPrograma(@ModelAttribute("programa") ClpbPrograma clpbPrograma,
			BindingResult result, SessionStatus status, HttpServletRequest request,Model modelMap) {
		
		try {
			
			modelMap.addAttribute("programa", clpbPrograma);
			modelMap.addAttribute("listaunidadmedidas", programaService.findUnidadMedidas());
			
			if (result.hasErrors()) {
				return "/programa/programaform";
			}

			Calendar daFechaInicioVigencia = null;
			Calendar daFechaFinVigencia    = null;
			String desFechaInicioVigencia  = clpbPrograma.getDesFechaInicioVigencia();
			String desFechaFinVigencia     = clpbPrograma.getDesFechaFinVigencia();
			Long id = clpbPrograma.getId();
			
			try{
				daFechaInicioVigencia = CalendarUtil.stringToCalendar(CLPConstantes.DATE_PATTERN, desFechaInicioVigencia);
			}catch(Exception e){
	        	saveError(request, getText("programaform.novalidafechainicio", request.getLocale()));
	        	return "/programa/programaform";
	        }
			
			try{
				daFechaFinVigencia = CalendarUtil.stringToCalendar(CLPConstantes.DATE_PATTERN, desFechaFinVigencia);
			}catch(Exception e){
	        	saveError(request, getText("programaform.novalidafechafin", request.getLocale()));
	        	return "/programa/programaform";
	        }
			
			clpbPrograma.setDaFechaInicioVigencia(daFechaInicioVigencia);
			clpbPrograma.setDaFechaFinVigencia(daFechaFinVigencia);
			
			if(id != null){
				String descripcion = programaService.validateProgramasCompatibles(clpbPrograma);
				if(ValidationUtil.isValidateString(descripcion)){
					
					saveError(request, getText("programaform.noprocede.incompatibilidad",descripcion, request.getLocale()));
		        	return "/programa/programaform";
				}
			}
			
			Map mapMsg = programaService.saveOrUpdatePrograma(clpbPrograma);
			if(mapMsg.get(CLPConstantes.MSG).toString().equals(CLPConstantes.SUCCESS)){
			        if(id == null){
				        saveMessage(request, getText("programaform.added", request.getLocale()));
			        }else{
				        saveMessage(request, getText("programaform.updated", request.getLocale()));
			        }	
			}else{
				
				if(mapMsg.get("detalle") != null){
					saveError(request, mapMsg.get("detalle").toString());
					return "/programa/programaform";
				}else{
					saveError(request, getText("errors.general", request.getLocale()));
					return "/programa/programaform";	
				}
			}
			
			return "redirect:programalist.html";
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/programa/programaform";
		}
	}
}
